package com.neurotech.pcc.widgets

import android.content.Context
import android.graphics.Color
import android.support.v4.content.ContextCompat
import android.text.Editable
import android.text.InputFilter
import android.text.TextUtils
import android.text.TextWatcher
import android.text.method.DigitsKeyListener
import android.text.method.ReplacementTransformationMethod
import android.util.AttributeSet
import android.view.Gravity
import android.view.KeyEvent
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import com.neurotech.pcc.R
import java.util.regex.Pattern


/**
 * Mac地址输入框
 * Created by shenhua on 2018/10/11.
 * @author shenhua
 *         Email shenhuanet@126.com
 */
class MacInputLayout @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null, defAttrStyle: Int = 0)
    : LinearLayout(context, attributeSet, defAttrStyle) {

    private var current = 0
    private var edits: List<MacEditText> = ArrayList()

    init {
        orientation = HORIZONTAL
        val layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        layoutParams.weight = 1f
        val inputListener = object : InputListener {
            override fun onPrevious() {
                if (current > 0) {
                    edits[current - 1].requestFocus()
                }
            }

            override fun onNext() {
                if (current < edits.size - 1) {
                    edits[current + 1].requestFocus()
                }
            }
        }

        val macEditText1 = MacEditText(context, inputListener)
        val macEditText2 = MacEditText(context, inputListener)
        val macEditText3 = MacEditText(context, inputListener)
        val macEditText4 = MacEditText(context, inputListener)
        val macEditText5 = MacEditText(context, inputListener)
        val macEditText6 = MacEditText(context, inputListener)

        addView(macEditText1, layoutParams)
        addView(DotTextView(context))
        addView(macEditText2, layoutParams)
        addView(DotTextView(context))
        addView(macEditText3, layoutParams)
        addView(DotTextView(context))
        addView(macEditText4, layoutParams)
        addView(DotTextView(context))
        addView(macEditText5, layoutParams)
        addView(DotTextView(context))
        addView(macEditText6, layoutParams)

        edits = object : ArrayList<MacEditText>() {
            init {
                add(macEditText1)
                add(macEditText2)
                add(macEditText3)
                add(macEditText4)
                add(macEditText5)
                add(macEditText6)
            }
        }

        for (i in edits.indices) {
            edits[i].setOnFocusChangeListener { _, _ ->
                current = i
            }
        }
    }

    fun fitMac(ip: String?) {
        if (TextUtils.isEmpty(ip)) {
            return
        }
        val ips = ip?.split(":")
        for (i in edits.indices) {
            edits[i].setText(ips?.get(i))
            edits[i].setSelection(ips?.get(i)?.length!!)
        }
    }

    fun mac(): String {
        var result = ""
        for (i in edits.indices) {
            result += edits[i].text.toString().toUpperCase() + ":"
        }
        return result.substring(0, result.length - 1)
    }

    companion object {
        fun isMac(addr: String): Boolean {
            if (addr.isEmpty() || addr.length < 12) {
                return false
            }
            val rexp = "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})\$"
            val pat = Pattern.compile(rexp)
            val mat = pat.matcher(addr)
            return mat.find()
        }
    }

    inner class MacEditText constructor(context: Context, inputListener: InputListener?) : EditText(context) {

        init {
            maxLines = 1
            keyListener = DigitsKeyListener.getInstance("0123456789ABCDEFabcdef")
            filters = arrayOf<InputFilter>(InputFilter.LengthFilter(2))
            gravity = Gravity.CENTER
            isFocusable = true
            transformationMethod = AutoCaseTransformationMethod()
//            background = ColorDrawable(Color.TRANSPARENT)
            addTextChangedListener(object : TextWatcher {
                override fun afterTextChanged(s: Editable?) {
                    if (s != null && s.isNotEmpty()) {
                        if (s.length == 2) {
                            inputListener?.onNext()
                        }
                    }
                }

                override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    normal()
                }
            })

            setOnKeyListener { _, keyCode, event ->
                if (keyCode == KeyEvent.KEYCODE_DEL && event.action == KeyEvent.ACTION_DOWN) {
                    if (text.isEmpty()) {
                        inputListener?.onPrevious()
                    }
                }
                return@setOnKeyListener false
            }
        }

        fun error() {
            setTextColor(Color.RED)
        }

        fun normal() {
            setTextColor(ContextCompat.getColor(context, R.color.colorPrimary))
        }
    }

    inner class AutoCaseTransformationMethod : ReplacementTransformationMethod() {

        override fun getOriginal() = charArrayOf('a', 'b', 'c', 'd', 'e', 'f')

        override fun getReplacement() = charArrayOf('A', 'B', 'C', 'D', 'E', 'F')
    }

    inner class DotTextView constructor(context: Context) : TextView(context) {
        init {
            text = ":"
            gravity = Gravity.BOTTOM
        }
    }

    interface InputListener {
        fun onPrevious()
        fun onNext()
    }
}